import router from '@/router'
import XEUtils from "xe-utils"
import useUserStore from '@/store/modules/store-user'
import { TokenUtils } from '@/utils/auth/index'

const whiteList = ['/login', 'LoginView']

/**
 * 退出登录
 */
const logout = function (next) {
	useUserStore().logOut().then(() => {
		next({ path: '/login' })
	})
}

// 全局路由导航守卫
router.beforeEach((to, from, next) => {
	// 1 跳转登录页面
	const isToken = TokenUtils.checkAuthorization()
	// 1 校验本地token
	if (isToken) {
		// 存在token
		if (to.path === '/login') {
			next({ path: '/' })
		} else {
			if (XEUtils.isEmpty(useUserStore().userInfo)) {
				// 获取秘钥
				useUserStore().getSecretKey();
				// 获取用户信息
				useUserStore().getInfo().then((res) => {
					next({ ...to, replace: true })
				}).catch(err => {
					console.error(err)
					logout(next)
				})
			} else {
				next()
			}
		}
	} else {
		// 不存在token
		if (whiteList.includes(to.path)) {
			next()
		} else {
			next(`/login?redirect=${to.fullPath}`)
		}
	}
})

